﻿using System;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;

namespace Autorun
{
	public partial class MainServerForm : Form
	{
		#region "Constructor and Form's Event Handlers"
		public MainServerForm()
		{
			InitializeComponent();
		}

		private void ServerForm_Load(object sender, EventArgs e)
		{
			Version ver;

			// === Set Program Information ============================================
			ver = new Version(Application.ProductVersion);
#if DEBUG
			Text = String.Format("[DEBUG] {0}", String.Format(Text, Application.ProductName, ApplicationStartInfo.StartMode.ToString(), ver.Major, ver.Minor, ver.Build, ver.Revision));
#else
			Text = String.Format(Text, Application.ProductName, ApplicationStartInfo.StartMode.ToString(), ver.Major, ver.Minor, ver.Build, ver.Revision);
#endif

			BackgroundImage = Properties.Resources.SplashScreen_2;

			LoadIcons();
			miniStats1.IsActive = true;
			myTimer.Enabled = true;
			myTimer_Tick(null, null);
		}

		private void ServerForm_FormClosing(object sender, FormClosingEventArgs e)
		{
			ServiceManagement.Instance.Stop();
		}
		#endregion

		#region "Procedures"
		private void LoadIcons()
		{
			Icon = Properties.Resources.icoLogo;

			imgStatus.Image = Properties.Resources.state_disconnected.ToBitmap();

			mySystray.Icon = Icon;
			mySystray.Text = Text;
		}
		#endregion

		#region "Data Access Methods"
		private void ExecuteNonQuery(string query)
		{
			SqlConnection cn;
			SqlCommand cmd;

			cn = new SqlConnection(Properties.Settings.Default.ConnectionString);

			try
			{
				cn.Open();
				cmd = cn.CreateCommand();
				cmd.CommandText = query;
				cmd.ExecuteNonQuery();
				cmd.Connection = null;
				cmd = null;
			}
			finally
			{
				cn.Close();
			}
		}

		private object ExecuteScalar(string query)
		{
			SqlConnection cn;
			SqlCommand cmd;
			object rc = null;

			cn = new SqlConnection(Properties.Settings.Default.ConnectionString);

			try
			{
				cn.Open();
				cmd = cn.CreateCommand();
				cmd.CommandText = query;
				rc = cmd.ExecuteScalar();
				cmd.Connection = null;
				cmd = null;
			}
			finally
			{
				cn.Close();
			}

			return rc;
		}

		private DataTable ExecuteDataTable(string query)
		{
			SqlDataAdapter da;
			DataSet rc;

			da = new SqlDataAdapter(query, Properties.Settings.Default.ConnectionString);
			rc = new DataSet();
			da.Fill(rc);
			return rc.Tables.Count != 0 ? rc.Tables[0] : null;
		}
		#endregion

		#region "Controls Events Handlers"
		private void myTimer_Tick(object sender, EventArgs e)
		{
			ServiceManagement svc;
			ConfigurationManagement cfg;
			ScheduleManagement sch;
			int maxValue;

			svc = ServiceManagement.Instance;
			cfg = ConfigurationManagement.Instance;
			sch = ScheduleManagement.Instance;

			// === Refresh the status icon =========================================
			switch (svc.Status)
			{
				case ServiceStatuses.Running:
					imgStatus.Image = Properties.Resources.state_started.ToBitmap();
					break;
				case ServiceStatuses.Stopped:
					imgStatus.Image = Properties.Resources.state_stopped.ToBitmap();
					break;
				default:
					imgStatus.Image = Properties.Resources.state_disconnected.ToBitmap();
					break;
			}

			// === Refresh the running progress bar ================================
			if (pbRunning.Maximum != cfg.ThreadPoolSize)
			{
				maxValue = (cfg.ThreadPoolSize > svc.RunningTaskCount ? cfg.ThreadPoolSize : svc.RunningTaskCount);
				pbRunning.Value = (pbRunning.Value > maxValue ? maxValue : pbRunning.Value);
				pbRunning.Maximum = maxValue;
			}
			if (pbRunning.Value != svc.RunningTaskCount)
				pbRunning.Value = svc.RunningTaskCount;
			lblRunning.Text = string.Format("{0}/{1}", svc.RunningTaskCount, cfg.ThreadPoolSize);


			// === Refresh the waiting progress bar ===================================
			if (pbWaiting.Maximum != sch.WaitingTasksCountMax)
			{
				pbWaiting.Value = 0;
				pbWaiting.Maximum = sch.WaitingTasksCountMax;
			}
			if (pbWaiting.Value != sch.WaitingTasksCount)
				pbWaiting.Value = sch.WaitingTasksCount;
			lblWaiting.Text = string.Format("{0}/{1}", sch.WaitingTasksCount, sch.WaitingTasksCountMax);
		}

		private void mnuQuit_Click(object sender, EventArgs e)
		{
			Close();
		}

		private void ClientForm_Resize(object sender, EventArgs e)
		{
			if (WindowState == FormWindowState.Minimized)
			{
				Hide();
				mySystray.Visible = true;
			}
		}

		private void btnRestore_Click(object sender, EventArgs e)
		{
			Show();

			WindowState = FormWindowState.Normal;
			mySystray.Visible = false;
			ShowInTaskbar = true;
		}

		private void mySystray_MouseDoubleClick(object sender, MouseEventArgs e)
		{
			btnRestore_Click(null, null);
		}
		#endregion

	}
}
